package com.talent.jiwen_teacher;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.liveaa.livemeeting.sdk.biz.core.ABCLiveSDK;
import com.talent.jiwen_teacher.base.BaseActivity;
import com.talent.jiwen_teacher.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen_teacher.http.common.ApiFactory;
import com.talent.jiwen_teacher.http.common.HttpUtil;
import com.talent.jiwen_teacher.http.common.ProgressSubscriber;
import com.talent.jiwen_teacher.http.result.LoginResult;
import com.talent.jiwen_teacher.util.MyToast;
import com.talent.jiwen_teacher.util.SPConstant;
import com.talent.jiwen_teacher.util.SPUtil;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.functions.Consumer;
import rx.Observable;

/**
 * Created by qyqx
 * 登录页
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {


    private String phoneString;
    private String passwordString;
    private String verifyCode;

    @BindView(R.id.indicator)
    MagicIndicator indicator;

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    @BindView(R.id.de_login_sign)
    Button mConfirm;

    @BindView(R.id.de_login_register)
    TextView mRegister;

    @BindView(R.id.de_login_forgot)
    TextView forgetPassword;

    @BindView(R.id.flagIv)
    ImageView flagIv;

    private List<Fragment> fragmentList = new ArrayList<>();
    private List<String> titleList = new ArrayList<>();

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public String titleName() {
        return null;
    }


    @SuppressLint("CheckResult")
    @Override
    protected void initData() {
        StatusBarUtil.setColor(this, Color.parseColor("#2F6097"), 100);
        setHeadVisibility(View.GONE);
        initView();
        RxPermissions rxPermissions = new RxPermissions(this);//Manifest.permission.FLASHLIGHT, Manifest.permission.READ_LOGS,
        rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.CALL_PHONE, Manifest.permission.BLUETOOTH)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
//                            MyToast.show(LoginActivity.this,"用户已经同意该权限");
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            MyToast.show(LoginActivity.this, "用户拒绝了该权限");
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』，提醒用户手动打开权限
                            MyToast.show(LoginActivity.this, "权限被拒绝，请在设置里面开启相应权限，若无相应权限会影响使用");
                        }
                    }
                });

    }


    private void initView() {
        forgetPassword.setOnClickListener(this);
        mConfirm.setOnClickListener(this);
        mRegister.setOnClickListener(this);

        titleList.clear();
        titleList.add("账号密码登录");
        titleList.add("手机快捷登录");

        fragmentList.clear();
        PasswordFragment pwdFragment = new PasswordFragment();
        pwdFragment.setListener(new PasswordFragment.OnPasswordFocusChangedListener() {
            @Override
            public void passwordEtFocus(boolean hasFocus) {
                if (hasFocus) {
                    flagIv.setImageResource(R.mipmap.iv_login_close_eyes);
                } else {
                    flagIv.setImageResource(R.mipmap.iv_login_show_eyes);
                }
            }
        });
        fragmentList.add(pwdFragment);
        fragmentList.add(new PhoneCodeLoginFragment());


        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return titleList == null ? 0 : titleList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {

                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);
                colorTransitionPagerTitleView.setNormalColor(ContextCompat.getColor(LoginActivity.this, R.color.text_gray_9));
                colorTransitionPagerTitleView.setSelectedColor(ContextCompat.getColor(LoginActivity.this, R.color.common_app_color));
                colorTransitionPagerTitleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                colorTransitionPagerTitleView.setText(titleList.get(index));
                colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        viewPager.setCurrentItem(index);
                    }
                });

                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_MATCH_EDGE);
                indicator.setColors(ContextCompat.getColor(LoginActivity.this, R.color.common_app_color));
                indicator.setLineHeight(6);
                return indicator;
            }
        });
        indicator.setNavigator(commonNavigator);

        viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return fragmentList.get(i);
            }

            @Override
            public int getCount() {
                return titleList.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titleList.get(position);
            }
        });

        ViewPagerHelper.bind(indicator, viewPager);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.de_login_sign:
                //先清空之前的数据
                phoneString = "";
                passwordString = "";
                verifyCode = "";

                if (viewPager.getCurrentItem() == 0) {
                    //账号密码登录
                    PasswordFragment passwordFragment = (PasswordFragment) fragmentList.get(viewPager.getCurrentItem());

                    phoneString = passwordFragment.getPhoneNumber();
                    passwordString = passwordFragment.getPassword();

                    if (TextUtils.isEmpty(phoneString)) {
                        showToast(getString(R.string.phone_number_is_null));
                        return;
                    }
                    if (TextUtils.isEmpty(passwordString)) {
                        showToast(getString(R.string.password_is_null));
                        return;
                    }
                    if (passwordString.contains(" ")) {
                        showToast(getString(R.string.password_cannot_contain_spaces));
                        return;
                    }
                    login(false);
                } else {
                    //手机快捷登录
                    PhoneCodeLoginFragment phoneCodeLoginFragment = (PhoneCodeLoginFragment) fragmentList.get(viewPager.getCurrentItem());

                    phoneString = phoneCodeLoginFragment.getPhoneNumber();
                    verifyCode = phoneCodeLoginFragment.getCode();

                    if (TextUtils.isEmpty(phoneString)) {
                        showToast(getString(R.string.phone_number_is_null));
                        return;
                    }
                    if (TextUtils.isEmpty(verifyCode)) {
                        showToast(getString(R.string.code_is_null));
                        return;
                    }
                    login(true);
                }
                break;
            case R.id.de_login_register:
                intentActivity(TeacherRegisterdActivity.class);
                break;
            case R.id.de_login_forgot:
                startActivityForResult(new Intent(this, ForgetPasswordActivity.class), 2);
                break;
        }
    }

    /**
     * 登录
     *
     * @param loginByCode
     */
    private void login(boolean loginByCode) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phoneString);
        if (loginByCode) {
            map.put("verifyCode", verifyCode);
        } else {
            map.put("password", passwordString);
        }
        map.put("resetStatus", "1");
        Observable observable = ApiFactory.getEducationApiSingleton().teacherLogin(map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<LoginResult>(this) {
            @Override
            protected void _onNext(LoginResult loginResult) {
                if (loginResult != null) {
//                    if(!Validators.isEmpty(loginResult.getNIMToken())){
                    JPushInterface.setAlias(mContext, (int) Math.random(), "t" + loginResult.getTeacherId());
                    SPUtil.stringIn(SPConstant.TOKEN, loginResult.getToken());
                    SPUtil.stringIn(SPConstant.USER_ID, loginResult.getTeacherId());
                    SPUtil.stringIn(SPConstant.USER_NAME, loginResult.getTeacherRealName());
                    SPUtil.stringIn(SPConstant.PHONE, loginResult.getTeacherPhone());
                    SPUtil.stringIn(SPConstant.PASSWORD, passwordString);
                    SPUtil.stringIn(SPConstant.USER_HEAD_URL, loginResult.getTeacherHeadImage());
                    SPUtil.stringIn(SPConstant.NIM_TOKEN, loginResult.getNIMToken());
                    SPUtil.stringIn(SPConstant.INVITE_CODE, loginResult.getInviteCode());
                    SPUtil.stringIn(SPConstant.TEACH_YEARS, "" + loginResult.getTeachAge());
                    SPUtil.intIn(SPConstant.TEACHER_IDENTITY, loginResult.getTeacherType());
                    SPUtil.intIn(SPConstant.TEACH_PART, loginResult.getGradePart());
                    SPUtil.intIn(SPConstant.SUBJECT_ID, loginResult.getSubjectId());
                    SPUtil.stringIn(SPConstant.SCHOOL_NAME, loginResult.getSchoolName());
                    SPUtil.stringIn(SPConstant.GRADUATE_SCHOOL_NAME, loginResult.getGraduatedSchool());
                    SPUtil.booleanIn(SPConstant.SHOW_WELFARE_DIALOG, true);

                    ABCLiveSDK.getInstance(LoginActivity.this).initToken(SPUtil.getBSToken());

                    if (loginResult.getUserStatus() == 3) {//用户状态（1：正常 2：未认证 3：未填写个人信息 9：注销）
//                      Toast.makeText(LoginActivity.this,"您未填写个人信息,无法认证,请点击左下方“注册”,补全信息",Toast.LENGTH_LONG).show();
//                        return;
                    } else if (loginResult.getUserStatus() == 9) {
                        showToast("您的账户被注销，请重新注册");
                        return;
                    }
                    intentActivity(IndexActivity.class);
                    finish();
                } else {
                    showToast(getString(R.string.data_is_wrong));
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2 && data != null) {
            String phone = data.getStringExtra("phone");
            String password = data.getStringExtra("password");

            PasswordFragment passwordFragment = (PasswordFragment) fragmentList.get(0);

            passwordFragment.setPhomeNumer(phone);
            passwordFragment.setPassword(password);

        } else if (data != null && requestCode == 1) {
            String phone = data.getStringExtra("phone");
            String password = data.getStringExtra("password");
            String nickname = data.getStringExtra("nickname");
            if (!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(nickname)) {
                PasswordFragment passwordFragment = (PasswordFragment) fragmentList.get(0);

                passwordFragment.setPhomeNumer(phone);
                passwordFragment.setPassword(password);
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private boolean backPressed;
    private Handler handler = new Handler();//再按一次退出

    @Override
    public void onBackPressed() {
        if (backPressed) {
            finish();
        } else {
            showToast("再按一次退出");
            backPressed = true;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    backPressed = false;
                }
            }, 2000L);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


}
